<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>axios</title>
</head>
<body>
<script src="node_modules/axios/dist/axios.min.js"></script>
<script>
//https://www.jianshu.com/p/df464b26ae58
//axios：它是一个类库，基于promise封装的ajax库
axios.defaults.baseURL = 'http://localhost:3000';//基础路径
axios.interceptors.response.use((res) => res.data);//设置拦截器直接获得data
// axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';


//get 配置需要写params，或者基于url后面拼接?传参也行不用params
axios.get('/category',{ //接口地址，配置选项
  params:{
    name:'abc',
    age:9
  }
}).then(res=>{
  //结果是一个对象，data主体内容，header响应头，request Ajax实例，
  //status状态码，statusText状态码描述，config配置项 有发请求的传参params
  console.log(res);
  let {data} = res;
}).catch(msg=>{
  //失败的原因
  console.log(msg)
})


//post 配置直接传对象
axios.post('/add',{
  name:'abc',
  age:9
}).then(res=>{
  //和get一样，config配置项 有发请求的传参data json格式字符串
  console.log(res);
  let {data} = res;
}).catch(msg=>{
  console.log(msg)
})
let obj = {name:'abc',age:9}
axios.post('/add',obj)


//head请求只有响应头没有响应主体
// axios.head('package.json').then(res=>{
//   console.log(res)
// }).catch(msg=>{
//   console.log(msg)
// });


//链式调用
axios.get('/category',{
  params:{id:1}
}).then(res=>{
  //拿到get请求的返回值，传给post的配置参数
  let {data} = res
  return axios.post('/add',{
    name:data.name
  })
}).then(res=>{
  //拿到post请求的返回值
  let {data} = res;
  console.log(data)
})

// axios.put();
// axios.delete();

/*
//实例用法
var instance = axios.create({
    baseURL: 'http://localhost:3000',
});
//配置传参用法
axios({
    method:"POST",
    url: 'http://localhost:3000',
    data: {id:1}
});
*/
</script>
</body>
</html>